import {
  useCallback,
  useEffect,
  useMemo,
  useState,
  forwardRef,
  useRef,
} from 'react';
import {
  Input,
  Row,
  Col,
  Button,
  Space,
  Empty,
  Spin,
  Popover,
  message,
  Popconfirm,
} from 'antd';
import { GlobalOutlined, PlusCircleOutlined } from '@ant-design/icons';
import { TextWidget, getMessage } from '@inbiz/react';
import { InbizIcon, getSiteLangType, getApp } from '@inbiz/utils';
import { toJS } from '@formily/reactive';
import { clone } from 'lodash';
import EditForm from './Component/editForm';
import { getLanguageList, getKindList } from './service';
import styles from './index.less';
// 默认多语言种类
const defaultLangKinds = [
  {
    KindName: '简体中文',
    KindCode: 'zh-cn',
  },
  {
    KindName: 'English',
    KindCode: 'en',
  },
  {
    KindName: '日本語',
    KindCode: 'ja',
  },
];

interface MultilingualItem {
  AppId?: string;
  Key: string;
  LangApplicable: 1 | 2 | 4 | 7;
  Kinds: {
    KindCode: string;
    KindName: string;
    LangText: string;
  }[];
}

interface MultilingualInputProps {
  value?: string;
  onChange?: Function;
  disabled?: boolean;
  onPressEnter?: (value: string) => void;
  onBlur?: (value: string) => void;
  placeholder?: string;
  bordered?: boolean;
  maxLength?: number;
  className?: string;
}

const MultilingualInput = (props: MultilingualInputProps, ref: any) => {
  const appInfo = getApp();

  // dropdown展开状态
  const [dropdownVisible, $dropdownVisible] = useState<boolean>(false);
  // Input框回显值
  const [showValue, $showValue] = useState<string>('');
  // 弹窗当前状态（列表、表单、绑定）
  const [type, $type] = useState<string>('list');
  // 列表加载状态
  const [listLoadding, $listLoadding] = useState<boolean>(true);
  // 回显加载状态
  const [recordLoadding, $recordLoadding] = useState<boolean>(false);
  // 列表数据
  const [dataList, $dataList] = useState<any[]>([]);
  // 多语言种类数据
  const [langList, $langList] = useState<any[]>([]);
  // 搜索值
  const [serchValue, $serchValue] = useState<string>('');
  // 当前绑定多语言
  const [activeLanguage, $activeLanguage] = useState<
    MultilingualItem | undefined
  >();
  // 当前数据是否是多语言
  const [isMultilingual, $isMultilingual] = useState<boolean>(false);
  // 列表搜索输入框值
  const [listSearchTxt, $listSearchTxt] = useState<string>('');
  // 搜索输入框组件ref
  const notFormRef = useRef<any>();
  // 是否执行Blur事件
  const isClickIcon = useRef(false);
  // 表单场景的表单id
  const formid = location.search?.replace?.('?', '')?.split?.('&')?.find((i: any) => i?.startsWith?.('formid='))?.replace?.('formid=', '')

  // 数据回显{multilingual}
  useEffect(() => {
    const pv = toJS(props.value);
    if (typeof pv === 'string' && pv.startsWith('{multilingual}')) {
      let value = pv.replace('{multilingual}', '').trim();
      $recordLoadding(true);
      $showValue(value);
      $isMultilingual(true);
      getLanguageList(
        {
          likeContext: value.replace('global.', ''),
          siteType: getSiteLangType(),
        },
        appInfo?.isWf as boolean,
        formid as string
      ).then((res) => {
        if (Array.isArray(res) && res.length) {
          $activeLanguage(res[0]);
        } else {
          $activeLanguage(undefined);
        }
        $recordLoadding(false);
      });
    } else {
      $showValue(pv || '');
      $activeLanguage(undefined);
      $isMultilingual(false);
    }
  }, [props.value]);

  // 获取语种数据
  const getLangDatas = useCallback(() => {
    getKindList(appInfo?.appId as string).then((res: any[]) => {
      let langkinds = defaultLangKinds;
      if (res && Array.isArray(res) && res.length) {
        langkinds = res.map((item: any) => {
          return {
            KindName: item.Name,
            KindCode: item.Code,
          };
        });
      }
      $langList(clone(langkinds));
    });
  }, []);

  // 输入框手动输入改变
  const inputChange = (val: string) => {
    $activeLanguage(undefined);
    $showValue(val);
    props.onChange?.(val);
  };

  // 获取多语言列表数据
  const getData = useCallback((searchTxt: string) => {
    $listLoadding(true);
    const params: { likeContext?: string; siteType: 1 | 2 | 4 | 7 } = {
      siteType: getSiteLangType(),
    };
    if (searchTxt && searchTxt !== '') {
      params.likeContext = searchTxt.trim();
    }
    $serchValue(searchTxt.trim());
    getLanguageList(params, appInfo?.isWf as boolean, formid as string)
      .then((res) => {
        if (Array.isArray(res)) {
          $dataList(res);
        } else {
          $dataList([]);
        }
        $listLoadding(false);
      })
      .catch(() => {
        $listLoadding(false);
        $dataList([]);
      });
  }, []);

  // Blur事件
  const handleBlur = useCallback(
    (e: any) => {
      if (!isClickIcon.current) {
        props.onBlur?.(e?.target?.value);
      }
    },
    [props.onBlur],
  );

  // 默认值搜索
  const defaultSearch = useCallback(() => {
    const searchTextDefault = getMessage(showValue) || '';
    $listSearchTxt(searchTextDefault);
    getData(searchTextDefault);
  }, [showValue]);

  // 多语言弹层组件
  const languageWindow = useMemo(() => {
    return (
      <div className={styles['multilingual-setter-language-window']}>
        {/* 多语言列表 */}
        {type === 'list' && (
          <>
            <Input
              className={styles['search-input']}
              placeholder={getMessage('MultilingualInput.input_placeholder')} // 搜索多语言
              suffix={
                <InbizIcon
                  type="icon-ic-sousuo"
                  style={{ color: '#999', cursor: 'pointer' }}
                  onClick={() => {
                    if (notFormRef && notFormRef.current) {
                      getData(notFormRef.current.input.value);
                    }
                  }}
                />
              }
              value={listSearchTxt}
              onChange={(e: any) => $listSearchTxt(e.target.value)}
              onPressEnter={(e: any) => {
                getData(e.target.value);
              }}
              ref={notFormRef}
            />
            {serchValue === '' ? (
              <Button
                type="text"
                icon={<PlusCircleOutlined style={{ marginRight: 8 }} />}
                className={styles['add-language-btn']}
                onClick={() => $type('add')}
              >
                <TextWidget>MultilingualInput.add_language</TextWidget>{' '}
                {/* 新建多语言 */}
              </Button>
            ) : (
              <div className={styles['add-language-btn-seatch']}>
                <span>
                  <TextWidget>MultilingualInput.search_no</TextWidget>{' '}
                  {/* 搜索结果不符合,  */}
                </span>
                &nbsp;
                <a onClick={() => $type('add')}>
                  <TextWidget>MultilingualInput.add_language</TextWidget>{' '}
                  {/* 新建多语言 */}
                </a>
              </div>
            )}
            <Spin spinning={listLoadding}>
              {Array.isArray(dataList) && dataList.length ? (
                <ul>
                  {dataList.map((item: any) => {
                    return (
                      <li key={item.Key}>
                        <Row>
                          <Col span={8}>
                            <TextWidget>MultilingualInput.only_key</TextWidget>
                            ： {/* 唯一标识： */}
                          </Col>
                          <Col span={16}>{item.Key}</Col>
                        </Row>
                        {Array.isArray(item.Kinds) &&
                          item.Kinds.map((val: any) => {
                            return (
                              <Row key={val.KindCode}>
                                <Col span={8}>{val.KindName}：</Col>
                                <Col span={16}>{val.LangText}</Col>
                              </Row>
                            );
                          })}
                        <div className={styles['window-item-shade']}>
                          <a
                            onClick={() => {
                              $activeLanguage(clone(item));
                              props.onChange?.(
                                `{multilingual}global.${item.Key}`,
                              );
                              $type('active');
                            }}
                          >
                            <TextWidget>
                              MultilingualInput.select_current_language
                            </TextWidget>
                            {/* 绑定此多语言 */}
                          </a>
                        </div>
                      </li>
                    );
                  })}
                </ul>
              ) : (
                <Empty
                  image={listLoadding ? null : Empty.PRESENTED_IMAGE_SIMPLE}
                  description={
                    listLoadding ? null : (
                      <TextWidget>MultilingualInput.no_data</TextWidget>
                    )
                  }
                /> // 暂无数据
              )}
            </Spin>
          </>
        )}
        {/* 添加表单 */}
        {type === 'add' && (
          <EditForm
            changeType={$type}
            appInfo={appInfo}
            formid={formid as string}
            active={clone(activeLanguage)}
            changeActive={(obj: MultilingualItem) => {
              $activeLanguage(obj);
              props.onChange?.(`{multilingual}global.${obj.Key}`);
            }}
            langList={clone(langList)}
          />
        )}
        {/* 选中多语言状态 */}
        {type === 'active' && (
          <Spin spinning={recordLoadding}>
            {typeof activeLanguage === 'object' ? (
              <div className={styles['active-language']}>
                <p>
                  <TextWidget>MultilingualInput.selected_language</TextWidget>
                  {/* 已成功绑定此多语言 */}
                </p>
                <div className={styles['language-item']}>
                  <Row>
                    <Col span={8}>
                      <TextWidget>MultilingualInput.only_key</TextWidget>：{' '}
                      {/* 唯一标识 */}
                    </Col>
                    <Col span={15} offset={1}>
                      {activeLanguage.Key}
                    </Col>
                  </Row>
                  {Array.isArray(activeLanguage.Kinds) &&
                    activeLanguage.Kinds.map((val: any) => {
                      return (
                        <Row key={val.KindCode}>
                          <Col span={8}>{val.KindName}：</Col>
                          <Col span={15} offset={1}>
                            {val.LangText}
                          </Col>
                        </Row>
                      );
                    })}
                </div>
                <Space align="end">
                  <Button onClick={() => $type('add')}>
                    <TextWidget>MultilingualInput.edit</TextWidget> {/* 修改 */}
                  </Button>
                  <Popconfirm
                    placement="topRight"
                    title={getMessage('MultilingualInput.confirm_unbind')} // 确认要取消绑定此多语言吗
                    onConfirm={() => {
                      let txt = getMessage(`global.${activeLanguage.Key}`)
                        .replace('global.', '')
                        .trim();
                      $activeLanguage(undefined);
                      props.onChange?.(txt);
                      $type('list');
                      getData('');
                      message.success(
                        getMessage(
                          'MultilingualInput.message_unbind_successful',
                        ),
                      ); // 已取消绑定多语言
                    }}
                    okText={getMessage('global.sure')} // 确认
                    cancelText={getMessage('global.cancel')} // 取消
                  >
                    <Button type="primary">
                      <TextWidget>MultilingualInput.unbind</TextWidget>{' '}
                      {/* 取消绑定 */}
                    </Button>
                  </Popconfirm>
                </Space>
              </div>
            ) : (
              <div className={styles['active-language']}>
                <Empty
                  image={Empty.PRESENTED_IMAGE_SIMPLE}
                  style={{ marginTop: '44px' }}
                  description={
                    <TextWidget>
                      MultilingualInput.no_searched_multilingual
                    </TextWidget>
                  } // 多语言已被删除，请重新绑定
                />
                <Space align="center">
                  <Button
                    type="primary"
                    onClick={() => {
                      $isMultilingual(false);
                      $type('list');
                      getData('');
                    }}
                  >
                    <TextWidget>MultilingualInput.go_bind</TextWidget>{' '}
                    {/* 去绑定 */}
                  </Button>
                </Space>
              </div>
            )}
          </Spin>
        )}
      </div>
    );
  }, [
    type,
    serchValue,
    dataList,
    listLoadding,
    activeLanguage,
    recordLoadding,
    listSearchTxt,
  ]);
  return (
    <>
      <div
        className={`${styles['inbiz-setter-multilingual-input']} multilingual-input ${props.className}`}
      >
        <Input
          bordered={props.bordered}
          placeholder={getMessage(props.placeholder)}
          value={getMessage(showValue)}
          disabled={Boolean(props.disabled)}
          onChange={(e: any) => inputChange(e.target.value)}
          onPressEnter={(e: any) => props.onPressEnter?.(e.target.value)}
          onBlur={handleBlur}
          maxLength={props.maxLength}
          ref={ref}
          suffix={
            <Popover
              overlayClassName={styles['popover-box']}
              content={languageWindow}
              visible={dropdownVisible}
              placement="bottomRight"
            >
              <a onClick={(e) => e.preventDefault()}>
                <GlobalOutlined
                  className={
                    props.disabled
                      ? styles['mutilingual-btn-disabled']
                      : isMultilingual
                        ? styles['mutilingual-btn-active']
                        : styles['mutilingual-btn']
                  }
                  onMouseDown={() => {
                    isClickIcon.current = true;
                    if (!props.disabled) {
                      if (!dropdownVisible) {
                        if (isMultilingual) {
                          // 已绑定多语言
                          $type('active');
                        } else {
                          // 未绑定多语言
                          $type('list');
                          $dataList([]);
                          defaultSearch();
                        }
                      }
                      // 打开多语言选择弹层
                      $dropdownVisible(true);
                      // 获取语种列表
                      getLangDatas();
                    }
                  }}
                  title={getMessage('MultilingualInput.multilingual')} // 多语言
                />
              </a>
            </Popover>
          }
        />
      </div>
      {dropdownVisible && (
        <div
          className={styles['dropdown-mask']}
          onClick={() => {
            $dropdownVisible(false);
            isClickIcon.current = false;
            props.onBlur?.(props.value!);
          }}
        ></div>
      )}
    </>
  );
};

export default forwardRef(MultilingualInput);
